﻿
using System;
using System.Data;
using System.Collections.Generic;
using System.IO;
using BYFW.SFL;

namespace LDSP.BRL
{
    public partial class Codification : BYFW.BOL.BaseEntity
    {
        public Codification()
        {
            m_tableName = "t_codification";
            m_hasName = true;
            m_hasComment = true;
        }

        protected int m_enterpriseID = 0;
        protected DateTime m_releaseDT = DateTime.Now;
        protected DateTime m_implementDT = DateTime.Now;
        protected bool m_isValid = true;
        protected int m_categoryID = 0;
        protected string m_organization = string.Empty;
        protected string m_referenceNumber = string.Empty;
        protected string m_fileName = string.Empty;
        protected string m_fileExtension = string.Empty;
        protected int m_catalogID = 0;
        protected DocType m_docType = DocType.法律法规;
        protected Enterprise m_enterprise = null;
        protected Category m_category = null;
        protected Catalog m_catalog = null;
        protected DateTime m_uploadDT = DateTime.Parse("1970-01-01");
        protected string m_summary = string.Empty;
        protected string m_keyItems = string.Empty;
        protected string m_invalid_Des = string.Empty;
        protected string m_invalid_list = string.Empty;
        protected int m_view_times = 0;
        protected bool m_isConverted = false;
        protected string m_PDFContent = string.Empty;

        protected string m_comment1 = string.Empty;
        protected string m_comment2 = string.Empty;
        protected string m_comment3 = string.Empty;
        protected string m_comment4 = string.Empty;
        protected string m_comment5 = string.Empty;

        /// <summary>
        /// 企业ID
        /// </summary>
        public int EnterpriseID
        {
            get { return m_enterpriseID; }
            set { m_enterpriseID = value; }
        }
        /// <summary>
        /// 发布时间
        /// </summary>
        public DateTime ReleaseDT
        {
            get { return m_releaseDT; }
            set { m_releaseDT = value; }
        }
        /// <summary>
        /// 实施时间
        /// </summary>
        public DateTime ImplementDT
        {
            get { return m_implementDT; }
            set { m_implementDT = value; }
        }
        /// <summary>
        /// 是否有效
        /// </summary>
        public bool IsValid
        {
            get { return m_isValid; }
            set { m_isValid = value; }
        }
        /// <summary>
        /// 类别ID
        /// </summary>
        public int CategoryID
        {
            get { return m_categoryID; }
            set { m_categoryID = value; }
        }
        /// <summary>
        /// 发布机构
        /// </summary>
        public string Organization
        {
            get { return m_organization; }
            set { m_organization = value; }
        }
        /// <summary>
        /// 发布文号
        /// </summary>
        public string ReferenceNumber
        {
            get { return m_referenceNumber; }
            set { m_referenceNumber = value; }
        }
        /// <summary>
        /// 文件名
        /// </summary>
        public string FileName
        {
            get { return m_fileName; }
        }
        /// <summary>
        /// 文件扩展名
        /// </summary>
        public string FileExtension
        {
            get { return m_fileExtension; }
        }
        /// <summary>
        /// 栏目ID
        /// </summary>
        public int CatalogID
        {
            get { return m_catalogID; }
            set { m_catalogID = value; }
        }
        /// <summary>
        /// 文档类型
        /// </summary>
        public DocType DocType
        {
            get { return m_docType; }
            set { m_docType = value; }
        }
        /// <summary>
        /// 上传时间
        /// </summary>
        public DateTime UploadDT
        {
            get { return m_uploadDT; }
            set { m_uploadDT = value; }
        }
        /// <summary>
        /// 概述
        /// </summary>
        public string Summary
        {
            get { return m_summary; }
            set { m_summary = value; }
        }
        /// <summary>
        /// 关键条款
        /// </summary>
        public string KeyItems
        {
            get { return m_keyItems; }
            set { m_keyItems = value; }
        }
        /// <summary>
        /// 失效描述
        /// </summary>
        public string InvalidDescription
        {
            get { return m_invalid_Des; }
            set { m_invalid_Des = value; }
        }
        /// <summary>
        /// 失效列表
        /// </summary>
        public string InvalidList
        {
            get { return m_invalid_list; }
            set { m_invalid_list = value; }
        }
        /// <summary>
        /// 查看次数
        /// </summary>
        public int ViewTimes
        {
            get { return m_view_times; }
            set { m_view_times = value; }
        }
        /// <summary>
        /// 是否转换过PDF文件
        /// </summary>
        public bool IsConverted
        {
            get { return m_isConverted; }
            set { m_isConverted = value; }
        }
        /// <summary>
        /// PDF文件内容
        /// </summary>
        public string PDFContent
        {
            get { return m_PDFContent; }
            set { m_PDFContent = value; }
        }


        /// <summary>
        /// 
        /// </summary>
        public string Comment1
        {
            get { return m_comment1; }
            set { m_comment1 = value; }
        }
        /// <summary>
        /// 
        /// </summary>
        public string Comment2
        {
            get { return m_comment2; }
            set { m_comment2 = value; }
        }
        /// <summary>
        /// 
        /// </summary>
        public string Comment3
        {
            get { return m_comment3; }
            set { m_comment3 = value; }
        }
        /// <summary>
        /// 
        /// </summary>
        public string Comment4
        {
            get { return m_comment4; }
            set { m_comment4 = value; }
        }
        /// <summary>
        /// 
        /// </summary>
        public string Comment5
        {
            get { return m_comment5; }
            set { m_comment5 = value; }
        }

        public Enterprise Enterprise
        {
            get
            {
                if (m_enterprise == null)
                {
                    m_enterprise = new Enterprise();
                    if (m_enterpriseID != 0)
                    {
                        m_enterprise.GetProperties(m_enterpriseID);
                    }
                }
                return m_enterprise;
            }
        }
        public Category Category
        {
            get
            {
                if (m_category == null)
                {
                    m_category = new Category();
                    if (m_categoryID != 0)
                    {
                        m_category.GetProperties(m_categoryID);
                    }
                }
                return m_category;
            }
        }
        public Catalog Catalog
        {
            get
            {
                if (m_catalog == null)
                {
                    m_catalog = new Catalog();
                    if (m_catalogID != 0)
                    {
                        m_catalog.GetProperties(m_catalogID);
                    }
                }
                return m_catalog;
            }
        }

        protected override void FillContainer()
        {
            base.FillContainer();
            m_container.Add("enterpriseID", m_enterpriseID);
            m_container.Add("releaseDT", m_releaseDT);
            m_container.Add("implementDT", m_implementDT);
            m_container.Add("isValid", m_isValid ? 1 : 0);
            m_container.Add("categoryID", m_categoryID);
            m_container.Add("organization", m_organization);
            m_container.Add("referenceNumber", m_referenceNumber);
            m_container.Add("fileName", m_fileName);
            m_container.Add("fileExtension", m_fileExtension);
            m_container.Add("catalogID", m_catalogID);
            m_container.Add("docType", (int)m_docType);
            m_container.Add("uploadDT", m_uploadDT);
            m_container.Add("summary", m_summary);
            m_container.Add("keyItems", m_keyItems);
            m_container.Add("invalidDescription", m_invalid_Des);
            m_container.Add("invalidList", m_invalid_list);
            m_container.Add("viewTimes", m_view_times);
            m_container.Add("isConverted", m_isConverted ? 1 : 0);
            if (!string.IsNullOrEmpty(m_PDFContent))
            {
                m_container.Add("PDFContent", m_PDFContent);
            }

            m_container.Add("comment1", m_comment1);
            m_container.Add("comment2", m_comment2);
            m_container.Add("comment3", m_comment3);
            m_container.Add("comment4", m_comment4);
            m_container.Add("comment5", m_comment5);
        }

        public override bool GetProperties(System.Data.DataRow record)
        {
            if (!base.GetProperties(record))
            {
                return false;
            }
            m_enterpriseID = this.GetIntValue(record, "enterpriseID");
            m_releaseDT = this.GetDateValue(record, "releaseDT");
            m_implementDT = this.GetDateValue(record, "implementDT");
            m_isValid = this.GetBoolValue(record, "isValid");
            m_categoryID = this.GetIntValue(record, "categoryID");
            m_organization = this.GetStringValue(record, "organization");
            m_referenceNumber = this.GetStringValue(record, "referenceNumber");
            m_fileName = this.GetStringValue(record, "fileName");
            m_fileExtension = this.GetStringValue(record, "fileExtension");
            m_catalogID = this.GetIntValue(record, "catalogID");
            m_docType = (DocType)this.GetIntValue(record, "docType");
            m_uploadDT = this.GetDateValue(record, "uploadDT");
            m_summary = this.GetStringValue(record, "summary");
            m_keyItems = this.GetStringValue(record, "keyItems");
            m_invalid_Des = this.GetStringValue(record, "invalidDescription");
            m_invalid_list = this.GetStringValue(record, "invalidList");
            m_view_times = this.GetIntValue(record, "viewTimes");
            m_isConverted = this.GetBoolValue(record, "isConverted");
            //m_PDFContent = this.GetStringValue(record, "PDFContent");

            m_comment1 = this.GetStringValue(record, "comment1");
            m_comment2 = this.GetStringValue(record, "comment2");
            m_comment3 = this.GetStringValue(record, "comment3");
            m_comment4 = this.GetStringValue(record, "comment4");
            m_comment5 = this.GetStringValue(record, "comment5");
            return true;
        }

        public List<Codification> GetListByCatalogID(int catalogID)
        {
            return this.GetSpecialList<Codification>(null, "catalogID", catalogID);
        }

        /// <summary>
        /// 由法规名模糊搜索法规。
        /// </summary>
        /// <param name="name"></param>
        /// <param name="implementationDate"></param>
        /// <returns></returns>
        public IList<Codification> GetCodificationByName(string name)
        {
            IList<Codification> result = new List<Codification>();

            string cond = string.Format("where {0} like '%{1}%'", DB.GetCol("name"), name);
            DataTable dt = this.GetRecords(cond);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    Codification cod = new Codification();
                    cod.GetProperties(row);

                    result.Add(cod);
                }
            }

            return result;
        }

        /// <summary>
        /// 由法规名和生效日期搜索法规。
        /// 若生效日期是Datetime.MinValue,则忽略生效日期。
        /// </summary>
        /// <param name="name"></param>
        /// <param name="implementationDate"></param>
        /// <returns></returns>
        public Codification GetCodification(string name, DateTime implementationDate)
        {
            Codification result = null;

            string cond = string.Format("where {0}={1}", DB.GetCol("name"), DB.GetVal(name));
            DataTable dt = this.GetRecords(cond);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    result = new Codification();
                    result.GetProperties(dt.Rows[0]);

                    if (implementationDate != DateTime.MinValue && result.ImplementDT.Date != implementationDate.Date)
                    {//若生效日期不匹配，则继续搜索。
                        result = null;
                    }
                    else
                    {//若生效日期匹配，则停止搜索。
                        break;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 由法规名和类型搜索法规。
        /// </summary>
        /// <param name="name"></param>
        /// <param name="implementationDate"></param>
        /// <returns></returns>
        public IList<Codification> GetCodification(string name, DocType type)
        {
            IList<Codification> result = new List<Codification>();

            string cond = string.Format("where {0} like '%{1}%' and docType = {2}", DB.GetCol("name"), name, DB.GetVal((int)type));
            DataTable dt = this.GetRecords(cond);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    Codification cod = new Codification();
                    cod.GetProperties(row);

                    result.Add(cod);
                }
            }

            return result;
        }

        /// <summary>
        /// 获取未实施法规列表
        /// </summary>
        /// <returns></returns>
        public List<Codification> GetUnImplementedCodification()
        {
            return this.GetSpecialList<Codification>(null, "where implementDT >= " + DB.GetVal(DateTime.Now.Date));
        }

        public void DeleteByCatalog(string transID, int catalogID)
        {
            List<Codification> docs = new Codification().GetListByCatalogID(catalogID);
            for (int i = 0; i < docs.Count; i++)
            {
                docs[i].Delete(transID);
            }
        }
        public void DeleteByEnterprise(string transID, int enterpriseID)
        {
            List<Codification> docList = this.GetSpecialList<Codification>(transID, "enterpriseID", enterpriseID);
            for (int i = 0; i < docList.Count; i++)
            {
                docList[i].Delete(transID);
            }
        }

        /// <summary>
        /// 删除Instance，删除文件，删除企业的适用关系，失效关系的源和目标包含它的都删除
        /// </summary>
        public override int Delete(string transID)
        {
            this.DeleteFile();
            //删除失效关系
            new R_DisableDoc().DeleteBySourceAndDestination(transID, m_id);
            //删除适用关系
            new R_EnterpriseCodification().DeleteByCodification(transID, m_id);
            return base.Delete(transID);
        }

        /// <summary>
        /// Delete the file if it exists
        /// </summary>
        private void DeleteFile()
        {
            string fileFullPath = this.GetDownloadFileFullName();
            if (File.Exists(fileFullPath))
            {
                File.Delete(fileFullPath);
            }
        }

        public string GetDownloadFileFullName()
        {
            try
            {
                return Path.Combine(LDSP.Util.CommonService.SITEROOT, "Docs", FileExtension);
            }
            catch { return ""; }
        }

        /// <summary>
        /// 根据filename创建fileextension
        /// </summary>
        public void CreateNewFile(string fileName)
        {
            this.DeleteFile();
            m_fileName = fileName;
            string ext = Path.GetExtension(m_fileName);
            m_fileExtension = Guid.NewGuid().ToString() + ext;
        }

        public DataTable GetRecordsByEnterpriseID(int enterpriseID)
        {
            string cond = string.Format("where {0}={1}", DB.GetCol("enterpriseID"), DB.GetVal(enterpriseID));
            return this.GetRecords(cond);
        }

        /// <summary>
        /// 获取系统管理员的法规，不考虑命中率排序
        /// </summary>
        /// <param name="cond"></param>
        /// <returns></returns>
        public DataTable GetRecordsForSystemAdmin(string cond)
        {
            string sql = string.Format(@"
select {0}, 
t2.fullpath 
from t_codification t, t_catalog t2
where t.catalogID=t2.id"
, GetFiled("t."));

            sql += String.IsNullOrEmpty(cond) ? "" : string.Format(" and {0}", DB.GetSimpleCondition(cond));

            return DB.Select(sql).Tables[0];
        }

        /// <summary>
        /// 获取系统管理员的法规，考虑命中率排序
        /// </summary>
        /// <param name="cond"></param>
        /// <returns></returns>
        public DataTable GetRecordsForSystemAdmin(string cond, string caculatedSelectFields)
        {
            string sql = string.Format(@"
select {0}, {1},
t2.fullpath 
from t_codification t, t_catalog t2
where t.catalogID=t2.id"
, GetFiled("t."), caculatedSelectFields);

            sql += String.IsNullOrEmpty(cond) ? "" : string.Format(" and {0}", DB.GetSimpleCondition(cond));

            return DB.Select(sql).Tables[0];
        }

        /// <summary>
        /// 获取系统管理员所有可操作的文档,不考虑命中率排序
        /// </summary>
        /// <param name="systemUserID"></param>
        /// <param name="cond"></param>
        /// <returns></returns>
        public DataTable GetRecordsBySystemUserID(int systemUserID, string cond)
        {
            string sql = string.Format("select {2} from t_codification t, t_r_systemUser_catalog t2 where t.catalogID = t2.catalogID and t2.systemUserID={0} and {1}",
                systemUserID,
                this.DB.GetSimpleCondition(cond),
                GetFiled("t."));
            return this.DB.Select(sql).Tables[0];
        }

        /// <summary>
        /// 获取系统管理员所有可操作的文档,考虑命中率排序
        /// </summary>
        /// <param name="systemUserID"></param>
        /// <param name="cond"></param>
        /// <returns></returns>
        public DataTable GetRecordsBySystemUserID(int systemUserID, string cond, string caculatedSelectFields)
        {
            string sql = string.Format("select {2},{3} from t_codification t, t_r_systemUser_catalog t2 where t.catalogID = t2.catalogID and t2.systemUserID={0} and {1}",
                systemUserID,
                this.DB.GetSimpleCondition(cond),
                GetFiled("t."),
                caculatedSelectFields);
            return this.DB.Select(sql).Tables[0];
        }

        /// <summary>
        /// 获取指定企业已授权的且未适用的所有文档,不考虑命中率排序
        /// </summary>
        /// <param name="enterpriseID"></param>
        /// <param name="cond"></param>
        /// <returns></returns>
        public DataTable GetRecordsByEnterpriseIDForAllUnFavorite(int enterpriseID, string cond)
        {
            string sql = string.Format(@"select 
{2},
t2.fullPath
from t_codification t, t_r_enterprise_catalog t1, t_catalog t2
where 
t.catalogID = t1.catalogID 
and t1.enterpriseID = {0} 
and t.catalogID = t2.id
and not exists (select 1 from t_r_enterprise_codification t3 where enterpriseID={0} and t.id = t3.docID)
and {1}
order by t.viewTimes desc
",
                                  enterpriseID,
                                  this.DB.GetSimpleCondition(cond),
                                  this.GetFiled("t.")
                                  );

            return this.DB.Select(sql).Tables[0];
        }

        /// <summary>
        /// 获取指定企业已授权的且未适用的所有文档,考虑命中率排序排序
        /// </summary>
        /// <param name="enterpriseID"></param>
        /// <param name="cond"></param>
        /// <returns></returns>
        public DataTable GetRecordsByEnterpriseIDForAllUnFavorite(int enterpriseID, string cond, string caculatedSelectFields)
        {
            string sql = string.Format(@"select 
{2},
{3},
t2.fullPath
from t_codification t, t_r_enterprise_catalog t1, t_catalog t2
where 
t.catalogID = t1.catalogID 
and t1.enterpriseID = {0} 
and t.catalogID = t2.id
and not exists (select 1 from t_r_enterprise_codification t3 where enterpriseID={0} and t.id = t3.docID)
and {1}
order by t.viewTimes desc
",
                                  enterpriseID,
                                  this.DB.GetSimpleCondition(cond),
                                  this.GetFiled("t."),
                                  caculatedSelectFields);

            return this.DB.Select(sql).Tables[0];
        }

        /// <summary>
        /// 查询企业适用法规，不考虑命中次数
        /// </summary>
        /// <param name="enterpriseID"></param>
        /// <param name="cond"></param>
        /// <returns></returns>
        public DataTable GetRecordsByEnterpriseFavorite(int enterpriseID, string cond)
        {
            string sql = string.Format(@"
select 
{1},
t1.id as ecID, 
t1.name as ecName, 
t1.comment as ecComment, 
t1.docID as ecDocID, 
t1.enterpriseID as ecEnterpriseID,
t1.favoriteDT as ecFavoriteDT, 
t1.priority as ecPriority,
t1.principal as ecPrincipal, 
t1.keyItems as ecKeyItems, 
t1.selfEvaluation as ecSelfEvaluation,
t2.fullPath
from t_codification t, t_r_enterprise_codification t1, t_catalog t2, t_r_enterprise_catalog t3 
where t.catalogID = t2.id and t.id = t1.docID and t3.enterpriseID={0} and t.catalogID = t3.catalogID and t1.enterpriseID = {0}",
                                  enterpriseID,
                                  this.GetFiled("t."));

            sql += string.IsNullOrEmpty(cond) ? "" : string.Format(" and {0} ", this.DB.GetSimpleCondition(cond));

            return this.DB.Select(sql).Tables[0];
        }

        /// <summary>
        /// 查询企业适用法规，考虑命中次数
        /// </summary>
        /// <param name="enterpriseID"></param>
        /// <param name="cond"></param>
        /// <returns></returns>
        public DataTable GetRecordsByEnterpriseFavorite(int enterpriseID, string cond, string caculatedSelectionFields)
        {
            string sql = string.Format(@"
select 
{1},
{2},
t1.id as ecID, 
t1.name as ecName, 
t1.comment as ecComment, 
t1.docID as ecDocID, 
t1.enterpriseID as ecEnterpriseID,
t1.favoriteDT as ecFavoriteDT, 
t1.priority as ecPriority,
t1.principal as ecPrincipal, 
t1.keyItems as ecKeyItems, 
t1.selfEvaluation as ecSelfEvaluation,
t2.fullPath
from t_codification t, t_r_enterprise_codification t1, t_catalog t2, t_r_enterprise_catalog t3 
where t.catalogID = t2.id and t.id = t1.docID and t3.enterpriseID={0} and t.catalogID = t3.catalogID and t1.enterpriseID = {0}",
                                  enterpriseID,
                                  this.GetFiled("t."),
                                  caculatedSelectionFields);

            sql += string.IsNullOrEmpty(cond) ? "" : string.Format(" and {0} ", this.DB.GetSimpleCondition(cond));

            return this.DB.Select(sql).Tables[0];
        }

        public DataTable GetRecordsUploadDate(DateTime oldest)
        {
            string cond = string.Format("where {0}>='{1}'", DB.GetCol("uploadDT"), oldest);
            return this.GetRecords(cond);
        }

        /// <summary>
        /// 企业用户删除文档时的操作
        /// </summary>
        /// <param name="enterpriseUser"></param>
        public void DeleteForEnterpriseUser(EnterpriseUser enterpriseUser)
        {
            //系统文档
            if (this.EnterpriseID == 0)
            {
                //获取列表目的：防止重复记录的脏数据
                List<R_EnterpriseCodification> list = new R_EnterpriseCodification().GetListByEnterpriseAndCodification(enterpriseUser.EnterpriseID, this.ID);
                foreach (var item in list)
                {
                    item.Delete();
                }
            }
            else
            {
                this.Delete();
            }
        }

        public Codification GetCodificationByReferenceNumber(string number)
        {
            Codification cod = null;

            List<Codification> cods = this.GetSpecialList<Codification>(null, string.Format("where {0} = {1}", DB.GetCol("referenceNumber"), DB.GetVal(number)));
            if (cods != null && cods.Count > 0)
            {
                cod = cods[0];
            }

            return cod;
        }

        public override DataTable GetRecords(string transID, string condition)
        {
            string sql = "select " + GetFiled() + " from " + DB.GetCol(TableName) + " " + condition;
            DataTable dt = DB.Select(sql, transID).Tables[0];
            if (!string.IsNullOrEmpty(m_defaultSort))
            {
                CommonOP.SortedTable(dt, m_defaultSort);
            }
            return dt;
        }

        private string GetFiled(string prefix = "")
        {
            return string.Format(m_field, prefix);
        }

        string m_field = @" {0}id
      ,{0}name
      ,{0}comment
      ,{0}enterpriseID
      ,{0}releaseDT
      ,{0}implementDT
      ,{0}isValid
      ,{0}categoryID
      ,{0}organization
      ,{0}referenceNumber
      ,{0}fileName
      ,{0}fileExtension
      ,{0}catalogID
      ,{0}docType
      ,{0}uploadDT
      ,{0}summary
      ,{0}keyItems
      ,{0}invalidDescription
      ,{0}comment1
      ,{0}comment2
      ,{0}comment3
      ,{0}comment4
      ,{0}comment5
      ,{0}invalidList
      ,{0}isConverted
      ,{0}viewTimes";
    }
}
